//
//  TbDetailVC.swift
//  LeGou
//
//  Created by lxm on 2022/7/28.
//

import UIKit

class TbDetailVC: ZMViewController, UIScrollViewDelegate {

    //MARK:--------------------属性--------------------
    let scrllHandler = ScrollFloatHandler()

    var id = ""
    // 商品分类
    var cid = 0
    
    var goodsInfo = ZMUtil.fastNilBehavior(type: TBGoodsDetail.self)
    var linkInfo : TBLinkInfo?
    // 新人购
    var newbuy = false
    
//    var linkInfo : TBLinkInfo?
    //MARK:--------------------UI控件--------------------
    @IBOutlet weak var navView: NavigationBarView!
    
    // 服务商提示
    @IBOutlet weak var vipContent: UIView!
    @IBOutlet weak var vipTip: UILabel!
    
    // 评价
    @IBOutlet weak var evaluateView: UIView!
    
    @IBOutlet weak var sku: UIButton!
    
    @IBOutlet weak var startView: HCSStarRatingView!
    
    @IBOutlet weak var banner: SDCycleScrollView!

    @IBOutlet weak var bottomContent: UIView!
    
    @IBOutlet weak var goodsListContent: UIView!
    
    @IBOutlet weak var scrollView: ScrollBgView!
    
    let goodsList = HomeListVC()
    
    @IBOutlet weak var someItemView: UIView!
    
    @IBOutlet weak var goodsContentH: NSLayoutConstraint!
    
    // 原价
    @IBOutlet weak var subPrice: UILabel!
    // 价格
    @IBOutlet weak var price: UILabel!
    // 销量
    @IBOutlet weak var saleCount: UILabel!
    // 名称
    @IBOutlet weak var name: UILabel!
    // 反多少
    @IBOutlet weak var couponPrice: UILabel!
    
    // 优惠券容器视图
    @IBOutlet weak var couponContentView: UIView!
    // 优惠券金额
    @IBOutlet weak var couponMoney: UILabel!
    // 优惠券名称
    @IBOutlet weak var couponName: UILabel!
    // 优惠券日期
    @IBOutlet weak var couponDate: UILabel!
    
    // 商品规格
    @IBOutlet weak var goodsSkuView: UIView!
    
    // 详情
    @IBOutlet weak var detailContent: TBDetailView!
    @IBOutlet weak var detailContentLab: UILabel!
    
    // 猜你喜欢父容器
    @IBOutlet weak var gussYLikeContent: UIView!
    
    // 首页
    @IBOutlet weak var homeView: UIStackView!
    // 收藏
    @IBOutlet weak var collectView: UIStackView!
    @IBOutlet weak var collectImg: UIImageView!
    // 分享赚
    @IBOutlet weak var shareBtn: UIButton!
    // 自购省
    @IBOutlet weak var buyBtn: UIButton!
    
    let loading = XMLoadingView()
    
    lazy var shareView: DetailShareView = {
        let v = DetailShareView()
        view.addSubview(v)
        v.snp.makeConstraints { make in
            make.bottom.equalTo(bottomContent.snp.top).offset(-5)
            make.centerX.equalToSuperview()
        }
        return v
    }()
    
    //MARK:--------------------生命周期--------------------
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        addConstraints()
        bindAction()
        loading.showInView(fatherView: view)
        getInfo()
    }
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        vipContent.style.GradientLeftToRight(left: "#363636".zm.hex(), right: "#212121".zm.hex())
        sku.layer.cornerRadius = sku.zm.height / 2
    }
    
    //MARK:--------------------UI--------------------
    func setUI() {
        title = ""
        hbd_barHidden = true
        buyBtn.titleLabel?.numberOfLines = 0
        buyBtn.titleLabel?.textAlignment = .center
        shareBtn.titleLabel?.numberOfLines = 0
        shareBtn.titleLabel?.textAlignment = .center
        collectView.isHidden = true
        evaluateView.isHidden = true
        goodsSkuView.isHidden = true
        shareBtn.isHidden = newbuy
        navView.contentView.backgroundColor = .clear
        navView.backgroundColor = .clear
        navView.autoBack = true
        navView.backButton.setImage(UIImage.init(named: "detail_back"), for: .normal)
        navView.backButton.backgroundColor = UIColor.zm.RGBA(r: 0, g: 0, b: 0, a: 0.55)
        navView.backButton.snp.updateConstraints { make in
            make.width.height.equalTo(36)
        }
        navView.backButton.layer.cornerRadius = 18
        
        startView.emptyStarImage = UIImage.init(named: "detail_star_e")?.withRenderingMode(.alwaysOriginal)
        startView.filledStarImage = UIImage.init(named: "detail_star")?.withRenderingMode(.alwaysOriginal)
        startView.value = 2
        
        banner.imageURLStringsGroup = ["http://yinongzhenxuan.oss-cn-beijing.aliyuncs.com/img/8799405d8f024d289bfce6b8f6695d56.png", "http://yinongzhenxuan.oss-cn-beijing.aliyuncs.com/img/8799405d8f024d289bfce6b8f6695d56.png"]
        banner.pageDotColor = "#999999".zm.hex()
        banner.currentPageDotColor = Style.mainColor
        banner.bannerImageViewContentMode = .scaleAspectFill
        banner.autoScroll = false
//        let v = DetailShareView()
//        v.isHidden = true
//        view.addSubview(v)
//        v.snp.makeConstraints { make in
//            make.bottom.equalTo(bottomContent.snp.top).offset(-5)
//            make.centerX.equalToSuperview()
//        }
        
        // godds list
        gussYLikeContent.isHidden = true
        goodsContentH.constant = 0
        goodsList.type = .tb_detail_like(goodsId: id, cid: cid)
        goodsListContent.addSubview(goodsList.view)
        goodsList.view.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        goodsList.guessLoadCallBack = { ok in
            if ok {
                self.gussYLikeContent.isHidden = false
                self.goodsContentH.constant = self.view.zm.height - self.bottomContent.zm.height - BottomSpace
            } else {
                self.goodsContentH.constant = 0
                self.gussYLikeContent.isHidden = true
            }
        }
        
        // scrollView delegate
        scrollView.delegate = self
        
        scrollView.gestureDelegate = scrllHandler
        scrllHandler.bgScollView = scrollView
        scrllHandler.floatView = someItemView
        scrllHandler.subScollObjc = goodsList
        
        // kvc设置 banner 的tag 为 999
        if let bannerCollection = banner.value(forKey: "mainView") as? UICollectionView {
            bannerCollection.tag = 999
        }
        
        if let user = ZMAppShareData.share.userInfo.value, user.serviceProviderLevel > 0 {
            vipTip.text = "服务商\(MineService.shared.LevelStr(level: user.serviceProviderLevel)), 最高可获得0元"
        } else {
            vipTip.text = "升级VIP，可赚到共富收益月入10万+"
        }
        
        if AppHelper.appVerify() {
            vipContent.isHidden = true
        }
    }
    
    func addConstraints() {
    }
    
    //MARK:--------------------methods--------------------
    @IBAction func onCopyToken(_ sender: UIButton) {
        getLinkInfo { obj in
            UIPasteboard.general.string = obj.longTpwd
            ZMToast.showToast(title: "口令已复制")
        }
    }
    
    @IBAction func onLevelUp(_ sender: UIButton) {
        tabBarController?.selectedIndex = 1
        self.navigationController?.popToRootViewController(animated: true)
//        router.push("xm://main/Mine/user_level")
    }
    
    func bindAction() {
        let couponContentViewTap = UITapGestureRecognizer()
        couponContentView.addGestureRecognizer(couponContentViewTap)
        couponContentViewTap.rx.event.subscribe(onNext: { [unowned self] recognizer in
            self.getLinkInfo { obj in
                if let url = URL(string: obj.couponClickUrl) {
                    if #available(iOS 10, *) {
                        UIApplication.shared.open(url)
                    } else {
                        UIApplication.shared.openURL(url)
                    }
                }
            }
        }).disposed(by: disposeBag)
        
        // 首页
        let homeTap = UITapGestureRecognizer()
        homeView.addGestureRecognizer(homeTap)
        homeTap.rx.event.subscribe(onNext: { [unowned self] recognizer in
            CATransaction.setCompletionBlock {
                guard let tab = UIApplication.shared.keyWindow?.rootViewController as? UITabBarController else {return}
                tab.selectedIndex = 0
            }
            CATransaction.begin()
            navigationController?.popToRootViewController(animated: true)
            CATransaction.commit()
        }).disposed(by: disposeBag)
        
        // 收藏
        let collectTap = UITapGestureRecognizer()
        collectView.addGestureRecognizer(collectTap)
        collectTap.rx.event.subscribe(onNext: { [unowned self] recognizer in
            ZMLog(message: "收藏")
        }).disposed(by: disposeBag)
        
        buyBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
            self.getLinkInfo(1) {obj in
                var linkUrl: URL?
                if let url = URL(string: obj.shortUrl) {
                    linkUrl = url
                } else if let url = URL(string: obj.itemUrl) {
                    linkUrl = url
                }
                if let url = linkUrl {
                    if #available(iOS 10, *) {
                        UIApplication.shared.open(url)
                    } else {
                        UIApplication.shared.openURL(url)
                    }
                } else {
                    ZMToast.showToast(title: "没有商品链接")
                }
            }
        }).disposed(by: disposeBag)
        
        goodsInfo.subscribe(onNext:{ [unowned self] resp in
            if let resp = resp {
                self.banner.imageURLStringsGroup = resp.imgs.split(separator: ",")
                self.price.attributedText = "¥".zm.attributedStr(attrs: [.font : Style.FONT_Open_Sans_SemiBold(14)])
                    .zm.append(str: resp.actualPrice.zm.toString(keep: 2), attri: ["f" : Style.FONT_Open_Sans_SemiBold(22)])
                self.saleCount.text = "销量：\(resp.monthSales)"
                self.name.text = resp.title
                self.couponPrice.text = "\(newbuy ? (resp.actualPrice > 5 ? 5.0 : resp.actualPrice) : resp.commission)"
                // subPrice
                self.subPrice.zm.setStrikethroughTitle(title: "¥" + resp.originalPrice.zm.toString(keep: 2))
                
                if resp.detailPics.count > 0 {
                    self.detailContent.loadImages(dataSorce: resp.detailPics.map({$0.img}))
                    self.detailContentLab.text = ""
                } else {
                    self.detailContentLab.text = resp.desc
                }
                // 优惠券
                if resp.couponId.count > 0 {
                    self.couponContentView.isHidden = false
                    self.couponMoney.text = resp.couponPrice.zm.toString(keep: 2)
                    self.couponDate.text = resp.couponStartTime.zm.stringToString(toFormate: "YYYY.MM.d") + "-" + resp.couponEndTime.zm.stringToString(toFormate: "YYYY.MM.d")
                } else {
                    self.couponContentView.isHidden = true
                }
                if let user = ZMAppShareData.share.userInfo.value, user.serviceProviderLevel > 0 {
                    vipTip.text = "服务商\(MineService.shared.LevelStr(level: user.serviceProviderLevel)), 可赚到共富收益月入10万+"
                } else {
                    vipTip.text = "升级VIP，可赚到共富收益月入10万+"
                }
                if resp.commission > 0 && !self.newbuy {
                    self.shareView.title.text = "分享给好友购买赚\(resp.quotaShare.zm.toString(keep: 2))额度"
                    self.shareBtn.setTitle("分享赚¥\(resp.commission)", for: .normal)
                } else {
                    self.shareBtn.setTitle("分享赚", for: .normal)
                }
                if self.newbuy {
                    self.buyBtn.setTitle("立即抢购", for: .normal)
                } else {
                    if resp.buyProvince > 0 {
                        self.buyBtn.setTitle("自购省¥\(resp.buyProvince.zm.toString(keep: 4))", for: .normal)
                    } else {
                        self.buyBtn.setTitle("自购省", for: .normal)
                    }
                }
            }
        }).disposed(by: disposeBag) 
    }
    
    func getInfo() {
        HomeAPI.tb_goods_detail(id).rxRequest(type: TBGoodsDetail.self).subscribe(onNext:{ [unowned self] resp in
            self.loading.hideView(anmation: true)
            self.goodsInfo.accept(resp)
        }, onError: { e in
            self.loading.showError(e.localizedDescription)
        }).disposed(by: disposeBag)
    }

    
    // 获取转链信息
    func getLinkInfo(_ promtionType: Int = 2, complete : @escaping (_ obj : TBLinkInfo)->()) {
        if LoginService.shared.checkLogin() == false {return}
//        if let obj = linkInfo {
//            complete(obj)
//        } else {
            if ZMAppShareData.share.userInfo.value?.relationId == "" {
                TBAuthTip.show { [unowned self] in

                    AlibcTradeUltimateSDK.sharedInstance().tradeService().authorize4AppKey("34031463", appName: "乐购惠生活", appLogo: UIImage.init(named: "icon_512"), currentVC: self) { e, token, exp in
                        if e != nil {
                            ZMToast.showToast(title: "授权失败")
                            return
                        }
                        guard let token = token else {
                            ZMToast.showToast(title: "token 为空")
                            return
                        }
                        ZMToast.showActivity()
                        HomeAPI.tb_userInfo(token).rxRequest(type: String.self).subscribe(onNext:{ [unowned self] resp in
                            if var user = ZMAppShareData.share.userInfo.value {
                                user.relationId = resp
                                ZMAppShareData.share.userInfo.accept(user)
                            }
                            let api = self.newbuy ? HomeAPI.tb_newbuy_koiling(self.id) : HomeAPI.tb_link_info(["goodsId":self.id, "promtionType":promtionType])
                            api.rxRequest(type: TBLinkInfo.self).subscribe(onNext:{ [unowned self] resp in
                                ZMToast.hiddenActivity()
                                self.linkInfo = resp
                                complete(resp)
                            }).disposed(by: self.disposeBag)
                        }).disposed(by: self.disposeBag)
                        
                    }
                }
            } else {
                ZMToast.showActivity()
                let api = self.newbuy ? HomeAPI.tb_newbuy_koiling(self.id) : HomeAPI.tb_link_info(["goodsId":self.id, "promtionType":promtionType])
                api.rxRequest(type: TBLinkInfo.self).subscribe(onNext:{ [unowned self] resp in
                    ZMToast.hiddenActivity()
                    self.linkInfo = resp
                    complete(resp)
                }).disposed(by: disposeBag)
            }
//        }
    }

    
    @IBAction func onShare(_ sender: Any) {
        getLinkInfo { [unowned self] obj in
            let v = ZMUtil.loadNibViewFullScreen(nibName: TBSharePOPView.self)
            v.goodsInfo.accept(self.goodsInfo.value!)
            v.linkInfo.accept(obj)
            self.view.addSubview(v)
        }
    }
    
    //MARK:--------------------delegate--------------------
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        scrllHandler.scrollViewDidScroll(scrollView)
    }
}
